package com.seawaterbt.springbootshiro.utils;

import com.seawaterbt.springbootshiro.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

public class ShiroUtil {

    //随机数生成器
    private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    //指定散列算法为md5
    private static String algorithmName = "MD5";
    //散列迭代次数
    private static final int HASH_ITERATIONS = 2;

    /**
     * 加密
     * @param user
     * @return
     */
    public static User encrypt(User user){
        //设置盐
        user.setSalt(randomNumberGenerator.nextBytes().toHex());
        String newPassword = new SimpleHash(algorithmName,user.getPassword(),ByteSource.Util.bytes(user.getSalt()),HASH_ITERATIONS).toHex();
        user.setPassword(newPassword);
        return user;
    }

    public static String encryptPwd(String password,String salt){
        return new SimpleHash(algorithmName,password,ByteSource.Util.bytes(salt),HASH_ITERATIONS).toHex();
    }

    public static boolean isAjax(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return true;
        }
        return false;
    }
}
